<?php


namespace app\common\model;


use app\api\model\UserException;
use think\Facade\Db;
use think\Exception;

class Wallet
{
    /**
     * 账户余额变动
     * @param int $user_id
     * @param float $money
     * @param int $is_add 1 增加 2 减少
     * @param int $log_type 参考config下wallet.php log_type
     * @param int $from_id
     * @param string $table
     */
    public static function addDelMoney($user_id, $money, $is_add, $log_type, $extra = "", $from_id = 0, $table = "")
    {
        if ($money <= 0) {
            throw new UserException('变动金额异常');
        }
        $user = Users::find($user_id);
        if ($is_add == 1) {
            if (in_array($log_type, [3, 4, 5, 6, 7, 8])) {
                $user->commission += $money;
            }
            $user->money += $money;
            $user->money_history += $money;
        } else {
            if ($user->money < $money) {
                throw new UserException('账户余额不足');
            }
            $user->money -= $money;
            $user->money_history -= $money;
        }
        $res = $user->save();
        if(!$res){
            throw new Exception('金额变动日志保存失败');
        }
        $insert_data = [
            'user_id' => $user_id,
            'money' => $money,
            'is_add' => $is_add,
            'log_type' => $log_type,
            'from_id' => $from_id,
            'table' => $table,
            'after_money' => $user->money,
            'extra' => $extra,
            'create_time'=>time(),
            'update_time'=>time()
        ];
        $res = Db::name("money_log")->insert($insert_data);
        if(!$res){
            throw new Exception('金额变动日志保存失败');
        }
    }


}